<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\admin\logic;



use app\common\model\zbtask\Money;
use app\common\utils\Utils;
use think\Db;
use think\exception\ValidateException;

class MoneyLogic
{
    private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例
    private $moneyDb;
    private function __construct() {
        $this->moneyDb = new Money();
    }

    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }

    public function getMoney($identity_card = '', $type = 'month', $createtime = 0) {
        if (!$identity_card) {
            throw new ValidateException('请正确传递身份证');
        }
        $createtime = $createtime ? $createtime : time();

        $user_id = Db::name('user')->where(['identity_card' => $identity_card])->value('id');
        if (!$user_id) {
            return 0;
        }

        $where['status'] = 1;
        $where['type'] = ['neq', 2];
        $where['user_id'] = $user_id;
        if ($type === 'month') {
            $time = Utils::getMonthStartEnd($createtime);
            $where['createtime'] = ['between', $time['strtotime']];
            $money =  $this->moneyDb->where($where)->sum('money');
        } else {
            $time = Utils::getYeartimes($createtime);
            $where['createtime'] = ['between', $time];
            $money =  $this->moneyDb->where($where)->sum('money');
        }

        return $money;
    }
    public function getMoneyByUserId( $user_id = 0, $type = 'month', $createtime = 0) {
        if (!$user_id) {
            return 0;
        }
        $createtime = $createtime ? $createtime : time();
        $where['status'] = 1;
        $where['type'] = ['neq', 2];
        $where['user_id'] = $user_id;
        if ($type === 'month') {
            $time = Utils::getMonthStartEnd($createtime);
            $where['createtime'] = ['between', $time['strtotime']];
            $money =  $this->moneyDb->where($where)->sum('money');
        } else {
            $time = Utils::getYeartimes($createtime);
            $where['createtime'] = ['between', $time];

            $money =  $this->moneyDb->where($where)->sum('money');
        }

        return $money;
    }


    private function __clone() {} //声明私有的克隆方法，防止对象被克隆

    public function __sleep() { //重写__sleep方法，将返回置空，防止序列化反序列化获得新的对象
        return [];
    }
}